<template>
  <div class="main">
    <div class="leftTree">
      <el-tree :data="treeData" :props="defaultProps" default-expand-all :expand-on-click-node="false" accordion @node-click="handleNodeClick" />
    </div>
    <div class="app-container tableDiv">
      <div class="filterDiv">
        <el-input v-model="listQuery.staffName" size="small" placeholder="职员代码/名称" style="width: 200px;" class="filter-item" />
        <el-button size="small" type="primary" round @click="handleFilter">查询</el-button>
        <el-button v-permiss="['60206270']" style="float:right;" size="small" type="primary" round @click="showImport">导入</el-button>
        <el-button v-permiss="['60206220']" style="float:right;" size="small" type="primary" round @click="handleAdd">新增</el-button>
      </div>
      <div class="contentDiv">
        <el-table :key="tableKey" v-loading="listLoading" :data="tableData" fit highlight-current-row style="width: 100%;" size="small">
          <el-empty slot="empty" :image-size="120" description="暂无数据" />
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="部门" prop="deptName" align="center" />
          <el-table-column label="职员代码" align="center">
            <template slot-scope="{row}">
              <span>{{ row.staffCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="职员名称" align="center">
            <template slot-scope="{row}">
              <span>{{ row.staffName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="信用额度" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{ row.creditLimit|Fixed }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已赊销金额" align="center" width="110">
            <template slot-scope="{row}">
              <span>{{ row.overdraftBalance|Fixed }}</span>
            </template>
          </el-table-column>
          <el-table-column label="销售改价" width="100" align="center">
            <template slot-scope="{row}">
              <span>{{ row.salePriceType == 1 ? '允许' : '不允许' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="退货改价" width="100" align="center">
            <template slot-scope="{row}">
              <span>{{ row.returnPriceType == 1 ? '允许' : '不允许' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="{row}">
              <span>{{ row.remarks }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否启用" align="center" width="90">
            <template slot-scope="{row}">
              <el-switch v-model="row.isDisable" :active-value="0" :inactive-value="1" @change="updateStatus($event, row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="{row}">
              <el-button v-permiss="['60206230']" type="text" size="small" @click="handleCompile(row)">编辑</el-button>
              <el-button v-permiss="['60206260']" type="text" size="small" @click="handleDel(row.id)">删除</el-button>
              <el-dropdown @command="handleCommand">
                <span class="ctrl">
                  更多
                  <i class="el-icon-arrow-right el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-permiss="['60206280']" :command="{row, command:1}">改信用额度</el-dropdown-item>
                  <el-dropdown-item v-permiss="['60206290']" :command="{row, command:2}">改已赊销金额</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" :title="dialogStatus=='create'?'新增职员':'修改职员'" :visible.sync="dialogVisible" width="600px">
      <el-form ref="dataForm" :rules="rules" :model="form" inline label-position="right" label-width="80px" style="width: 580px; margin-left:10px;">
        <el-form-item label="职员代码" prop="staffCode">
          <el-input v-model="form.staffCode" placeholder="职员代码" />
        </el-form-item>
        <el-form-item label="职员名称" prop="staffName">
          <el-input v-model="form.staffName" placeholder="职员名称" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <treeselect v-model="form.deptId" :options="treeData" :normalizer="normalizer" style="width:185px" placeholder="选择所属部门" />
        </el-form-item>
        <el-form-item label="信用额度" prop="creditLimit">
          <el-input v-model="form.creditLimit" placeholder="信用额度" />
        </el-form-item>
        <el-form-item label="销售改价" prop="salePriceType">
          <el-radio v-model="form.salePriceType" :label="1">允许</el-radio>
          <el-radio v-model="form.salePriceType" :label="0">不允许</el-radio>
        </el-form-item>
        <el-form-item label="退货改价" prop="returnPriceType" style="margin-left:40px">
          <el-radio v-model="form.returnPriceType" :label="1">允许</el-radio>
          <el-radio v-model="form.returnPriceType" :label="0">不允许</el-radio>
        </el-form-item>
        <el-form-item label="品牌权限" prop="isBrand">
          <el-radio v-model="form.isBrand" :label="1">控制</el-radio>
          <el-radio v-model="form.isBrand" :label="0">不控制</el-radio>
        </el-form-item>
        <el-form-item label="仓库权限" prop="isWarehouse" style="margin-left:40px">
          <el-radio v-model="form.isWarehouse" :label="1">控制</el-radio>
          <el-radio v-model="form.isWarehouse" :label="0">不控制</el-radio>
        </el-form-item>
        <el-form-item label="车辆权限" prop="isTruck">
          <el-radio v-model="form.isTruck" :label="1">控制</el-radio>
          <el-radio v-model="form.isTruck" :label="0">不控制</el-radio>
        </el-form-item>
        <el-form-item label="商品权限" prop="isItem" style="margin-left:40px">
          <el-radio v-model="form.isItem" :label="1">控制</el-radio>
          <el-radio v-model="form.isItem" :label="0">不控制</el-radio>
        </el-form-item>
        <el-form-item label="线路权限" prop="isRoute">
          <el-radio v-model="form.isRoute" :label="1">控制</el-radio>
          <el-radio v-model="form.isRoute" :label="0">不控制</el-radio>
        </el-form-item>
        <el-form-item label="客户权限" prop="isCust" style="margin-left:40px">
          <el-radio v-model="form.isCust" :label="1">控制</el-radio>
          <el-radio v-model="form.isCust" :label="0">不控制</el-radio>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="备注" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isDisable">
          <el-radio v-model="form.isDisable" :label="0">是</el-radio>
          <el-radio v-model="form.isDisable" :label="1">否</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus == 'create'?handleCreate():handleModify()">确定</el-button>
      </div>
    </el-dialog>
    <import-data ref="importRef" type="staff" title="职员" />
  </div>
</template>
<script>
import { getStaff, saveStaff, delStaff, getDeptTree, updateStaffDisabled, updateCreditLimitById, updateOverdraftBalanceById, getAllByDeptId } from '@/api/basedata'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import importData from './importData'
export default {
  name: 'BaseStaff',
  components: { Treeselect, importData },
  filters: {
    Fixed: function(num) {
      if (!num) {
        return '0.00'
      }
      return parseFloat(num).toFixed(2)
    }
  },
  data() {
    return {
      tableKey: 0,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'deptName'
      },
      tableData: [],
      deptId: '',
      curItemLeaf: '',
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        deptId: '',
        staffName: ''
      },
      showReviewer: false,
      form: {
        id: '',
        staffName: '',
        deptId: '',
        creditLimit: '',
        remarks: '',
        staffCode: '',
        salePriceType: 0,
        returnPriceType: 0,
        isCust: 0,
        isRoute: 0,
        isTruck: 0,
        isItem: 0,
        isBrand: 0,
        isWarehouse: 0,
        isDisable: 0
      },
      resetform: {
        id: '',
        staffName: '',
        deptId: '',
        remarks: '',
        creditLimit: '',
        staffCode: '',
        salePriceType: 0,
        returnPriceType: 0,
        isCust: 0,
        isRoute: 0,
        isTruck: 0,
        isItem: 0,
        isBrand: 0,
        isWarehouse: 0,
        isDisable: 0
      },
      dialogVisible: false,
      dialogStatus: '',
      rules: {
        staffName: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        staffCode: [
          { required: true, message: '代码不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        isDisable: [{ required: false }]
      }
    }
  },
  created() {
    this.getTree()
    this.getList()
  },
  methods: {
    showImport() {
      this.$refs.importRef.option = {
        show: true
      }
    },
    normalizer(node) {
      if (!node.children || (node.children && !node.children.length)) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children
      }
    },
    handleCommand(obj) {
      if (obj.command === 1) {
        this.handleUpdate1(obj.row.creditLimit, obj.row.id)
      }
      if (obj.command === 2) {
        this.handleUpdate2(obj.row.overdraftBalance, obj.row.id)
      }
    },
    handleNodeClick(e) {
      this.deptId = e.id
      this.curItemLeaf = e.leaf
      this.getStaffData()
    },
    getStaffData(id) {
      this.listLoading = true
      getAllByDeptId(this.deptId).then((res) => {
        this.listLoading = false
        this.tableData = res.data.data
      })
    },
    getTree() {
      getDeptTree({ parentId: '', includeRoot: 1 }).then((res) => {
        this.treeData = res.data.data
      })
    },
    getList() {
      this.listLoading = true
      getStaff(this.listQuery).then((res) => {
        this.listLoading = false
        this.tableData = res.data.data
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleUpdate1(val, id) {
      this.$prompt('请输入信用额度', '改信用额度', {
        closeOnClickModal: false,
        inputValue: parseFloat(val).toFixed(2) || '0.00',
        inputType: 'text',
        inputPattern: /^\d+$|^\d*\.\d*$/,
        inputErrorMessage: '格式不正确'
      }).then(({ value }) => {
        this.updateValue1(id, value)
      })
    },
    handleUpdate2(val, id) {
      this.$prompt('请输入已赊销金额', '改已赊销金额', {
        closeOnClickModal: false,
        inputValue: parseFloat(val).toFixed(2) || '0.00',
        inputType: 'text',
        inputPattern: /^\d+$|^\d*\.\d*$/,
        inputErrorMessage: '格式不正确'
      }).then(({ value }) => {
        this.updateValue2(id, value)
      })
    },
    updateValue1(id, value) {
      var obj = { id: id, creditLimit: value }
      updateCreditLimitById(obj).then((res) => {
        if (res.data.errorCode === '0') {
          this.getList()
          this.$message.success(res.data.msg)
        }
      })
    },
    updateValue2(id, value) {
      var obj = { id: id, overdraftBalance: value }
      updateOverdraftBalanceById(obj).then((res) => {
        if (res.data.errorCode === '0') {
          this.getList()
          this.$message.success(res.data.msg)
        }
      })
    },
    handleAdd() {
      if (this.curItemLeaf === 0) {
        this.$message.warning('只有末级部门才能添加')
        return
      }
      this.dialogVisible = true
      this.dialogStatus = 'create'
      for (var key in this.form) {
        this.form[key] = this.resetform[key]
      }
      this.form.deptId = this.deptId
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCompile(obj) {
      this.dialogVisible = true
      this.dialogStatus = 'update'
      for (var key in this.form) {
        this.form[key] = obj[key]
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    updateStatus(e, row) {
      this.changeAvaiable(e, row.id)
    },
    changeAvaiable(isDisable, id) {
      var obj = { isDisable, id }
      updateStaffDisabled(obj).then((res) => {
        if (res.data.errorCode === '0') {
          this.$message.success(res.data.msg)
        }
      })
    },
    handleDel(id) {
      this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        closeOnClickModal: false,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delItem(id)
      })
    },
    handleModify() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveStaff(this.form).then((res) => {
            if (res.data.errorCode == 0) {
              this.getList()
              this.dialogVisible = false
              this.$message.success(res.data.msg)
            }
          })
        }
      })
    },
    handleCreate() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.deptId = this.deptId
          saveStaff(this.form).then((res) => {
            if (res.data.errorCode == 0) {
              this.getList()
              this.dialogVisible = false
              this.$message.success(res.data.msg)
            }
          })
        }
      })
    },
    delItem(id) {
      delStaff(id).then((res) => {
        if (res.data.errorCode == 0) {
          this.getList()
          this.dialogVisible = false
          this.$message.success('删除成功')
        }
      })
    }
  }
}
</script>
<style scoped>
.main {
  position: relative;
  width: 100%;
  height: 100%;
  padding-left: 190px;
}

.leftTree {
  width: 180px;
  height: 100%;
  background-color: #fff;
  position: absolute;
  top: 10px;
  left: 10px;
  border: 1px #eee solid;
  padding: 10px 5px;
}

.tableDiv {
  width: 100%;
}

.fileDiv {
  width: 400px;
  height: 60px;
  border: 1px #d0d0d0 solid;
  line-height: 60px;
  text-align: center;
  border-radius: 6px;
}
.filter-item {
  position: relative;
}
/deep/.el-form-item {
  margin-bottom: 18px;
}

</style>
